/*
 * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
package com.sun.dtv.lwuit;

import com.sun.dtv.lwuit.geom.Dimension;
import com.sun.dtv.lwuit.plaf.Style;
import com.sun.dtv.lwuit.events.ActionEvent;
import com.sun.dtv.lwuit.events.ActionListener;
import com.sun.dtv.lwuit.layouts.BorderLayout;
import com.sun.dtv.lwuit.list.DefaultListCellRenderer;
import com.sun.dtv.lwuit.list.DefaultListModel;
import com.sun.dtv.lwuit.list.ListCellRenderer;
import com.sun.dtv.lwuit.list.ListModel;
import com.sun.dtv.lwuit.plaf.UIManager;
import java.util.Vector;

/**
 * A combo box is a list that allows only one selection at a time, when a user clicks
 * the combo box a popup button with the full list of elements allows the selection of
 * a single element. The combo box is driven by the list model and allows all the renderer
 * features of the List as well. 
 * 
 * @see List
 * @author Chen Fishbein
 */
public class ComboBox extends List {

    private static String id = "ComboBox";
    private Component popupContent;
    private List contained;
    private Popup popup;

    /** 
     * Creates a new instance of ComboBox 
     * 
     * @param items set of items placed into the combo box model
     */
    public ComboBox(Vector items) {
        this(new DefaultListModel(items));
    }

    /** 
     * Creates a new instance of ComboBox 
     * 
     * @param items set of items placed into the combo box model
     */
    public ComboBox(Object[] items) {
        this(new DefaultListModel(items));
    }

    /** 
     * Constructs an empty combo box
     */
    public ComboBox() {
        this(new DefaultListModel());
    }

    /**
     * Creates a new instance of ComboBox 
     * 
     * @param model the model for the combo box elements and selection
     */
    public ComboBox(ListModel model) {
        super(model);
        ((DefaultListCellRenderer)super.getRenderer()).setShowNumbers(false);
        setInputOnFocus(false);
        setIsScrollVisible(false);
    }

    /**
     * @inheritDoc
     */
    protected String getUIID() {
        return id;
    }

    /**
     * @inheritDoc
     */
    public void setSelectedIndex(int selection) {
        super.setSelectedIndex(selection, false);
    }
    
    /**
     * @inheritDoc
     */
    public void setSelectedIndex(int selection, boolean scroll) {
        super.setSelectedIndex(selection, false);
    }
    
    /**
     * @inheritDoc
     */
    public void setModel(ListModel m) {
        super.setModel(m);
        if (contained != null) {
            contained.setModel(m);
        }
    }

    /**
     * @inheritDoc
     */
    public void setHandlesInput(boolean handlesInput) {
        super.setHandlesInput(handlesInput);
        getPopup().setVisible(handlesInput);
        if (isSmoothScrolling()) {
            if (handlesInput) {
                getComponentForm().registerAnimated(((Container) popupContent).getComponentAt(0));
            } else {
                getComponentForm().deregisterAnimated(((Container) popupContent).getComponentAt(0));
            }
        }
    }

    private Component getPopupContent() {

        contained = new List(getModel());
        contained.setFixedSelection(FIXED_NONE_CYCLIC);
        contained.setListCellRenderer(getRenderer());
        contained.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                setHandlesInput(!handlesInput());
                fireActionEvent();
            }
        });
        Container cnt = new Container(new BorderLayout());
        cnt.addComponent(BorderLayout.CENTER, contained);
        contained.setStyle(UIManager.getInstance().getComponentStyle("ComboBoxPopup"));

        popupContent = cnt;
        return popupContent;
    }

    private Popup getPopup() {
        if (popup == null) {
            popup = new Popup(getComponentForm(), getPopupContent());
        } else {
            contained.setListCellRenderer(getRenderer());
            contained.setModel(getModel());
        }
        int y = getAbsoluteY() + getHeight();
        int height = Math.min(getComponentForm().getHeight() - y, popupContent.getPreferredSize().getHeight());
        
        // if there is not enough room to popup, open the popup upwards.
        if(getComponentForm().getHeight() - y < contained.getElementSize(true).getHeight() * 3) {
            height = contained.getElementSize(true).getHeight() * 3;
            y = getAbsoluteY() - height;
        }
        popupContent.setHeight(height);
        popupContent.setX(getAbsoluteX());
        popupContent.setY(y);
        popupContent.setWidth(getWidth());
        popupContent.setFixedPosition(true);
        Style s = popupContent.getStyle();
        s.merge(getStyle());
        s.setBgTransparency(0xFF);
        s.setBorder(null);
        s.setMargin(0, 0, 0, 0);
        s.setPadding(0, 0, 0, 0);
        return popup;
    }

    /**
     * Reset popup data on model change to allow the popup to refresh with the 
     * right details
     * 
     * @param status the model status
     */
    protected void modelChanged(int status) {
        popup = null;
        popupContent = null;
    }

    /**
     * @inheritDoc
     */
    public void pointerReleased(int x, int y) {
        setHandlesInput(true);
    }

    /**
     * @inheritDoc
     */
    public void paint(Graphics g) {
        UIManager.getInstance().getLookAndFeel().drawComboBox(g, this);
    }

    /**
     * @inheritDoc
     */
    protected Dimension calcPreferredSize() {
        return UIManager.getInstance().getLookAndFeel().getComboBoxPreferredSize(this);
    }
}
